package org.theSeed.redisIntegration.config;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.theSeed.redisIntegration.pojo.prop.RedisProp;
import java.time.Duration;

@Configuration
@AutoConfigureBefore(CacheAutoConfiguration.class)
public class SeedCacheManagerConfig {

    /**
     * 配置cacheManager
     *
     */
    @Bean(name = "cacheManager")
    public RedisCacheManager cacheManager(RedisConnectionFactory factory, RedisProp redisProp) {
        //默认的redisCahce配置，此处我们没用，而是自己配置
        //RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 设置缓存的默认过期时间
                .entryTtl(Duration.ofSeconds(redisProp.getCacheManagerSecond()))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(SeedJsonJacksonCodec.objectMapper)))
                // 不缓存空值
                .disableCachingNullValues()
                .prefixCacheNameWith(redisProp.getKeyPrefix()+redisProp.getManagerKeyPrefix());
        //根据redis缓存配置和reid连接工厂生成redis缓存管理器
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        return redisCacheManager;
    }
}
